package ui.home.column3.chat

import androidx.compose.foundation.*
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.selection.SelectionContainer
import androidx.compose.material.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.ExperimentalComposeUiApi
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.painter.BitmapPainter
import androidx.compose.ui.input.pointer.PointerEventType
import androidx.compose.ui.input.pointer.onPointerEvent
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import model.repository.UserRepository
import model.vo.MessageContentItem
import theme.EasyChatTheme
import ui.compose.NetworkImage
import ui.custom_context_menu.CustomLocalContextMenuRepresentation
import ui.custom_context_menu.CustomTextContextMenu
import ui.custom_context_menu.CustomTextMenuProvider
import utils.TimeStringUtil


/**
 * @author wei kunJie
 * @date 2024/3/12 13:39:46
 */
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun MessageContent(easyChatTheme: MutableState<EasyChatTheme>,modifier: Modifier, messageContentItems: MutableList<MessageContentItem>) {
    val isActivityVerticalScrollbar = remember { mutableStateOf(false) }
    Box(modifier = modifier
        .onPointerEvent(PointerEventType.Enter) { isActivityVerticalScrollbar.value = true }
        .onPointerEvent(PointerEventType.Exit) { isActivityVerticalScrollbar.value = false }) {
        val state = rememberLazyListState()
        //渲染列表
        LazyColumn(modifier = Modifier.fillMaxSize(), state = state,reverseLayout = true) {
            items(messageContentItems) { item ->
                MessageContentRow(message = item, easyChatTheme = easyChatTheme)
            }
        }
        //只有当鼠标进入时才出现滚动条
        if (isActivityVerticalScrollbar.value) {
            VerticalScrollbar(
                modifier = Modifier.align(Alignment.CenterEnd).fillMaxHeight(),
                adapter = rememberScrollbarAdapter(
                    scrollState = state
                ),
                reverseLayout = true
            )
        }
    }
}

/**
 * Item
 */
@Composable
fun MessageContentRow(easyChatTheme: MutableState<EasyChatTheme>,message: MessageContentItem) {
    val isCurrentUser = UserRepository.user?.account == message.userAccount
    Row(
        horizontalArrangement = if (isCurrentUser) Arrangement.End else Arrangement.Start,
        modifier = Modifier.padding(horizontal = 21.dp, vertical = 9.dp)
    )
    {
        //判断是自己发出的信息还是别人发的
        //自己的渲染在右边
        //别人的渲染在左边
        if (!isCurrentUser) {
            //别人的
            //头像
            NetworkImage(
                url = message.userHeadImageUrl,
                painterFor = { remember { BitmapPainter(it) } },
                contentDescription = message.userName+"的头像",
                modifier = Modifier.size(40.dp).clip(CircleShape),
                contentScale = ContentScale.Crop,
                defaultPainterFor = painterResource("image/default_head.png")
            )
            Column(modifier = Modifier.padding(start = 10.dp)) {
                //用户名和时间
                Row(
                    horizontalArrangement = Arrangement.Start,
                    modifier = Modifier.padding(bottom = 5.dp)
                ) {
                    Text(text = message.userName, color = Color(0xFF656565), fontSize = 14.sp)
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(text = TimeStringUtil.getTimeString(message.time), color = Color(0xFF656565), fontSize = 14.sp)
                }
                //别人的消息气泡、消息内容
                ContextText(text = message.content, easyChatTheme = easyChatTheme)
            }
            Spacer(modifier = Modifier.width(50.dp))
        } else {
            //自己的
            Spacer(modifier = Modifier.width(50.dp))
            Column(modifier = Modifier.weight(1f).padding(end = 5.dp)) {
                //用户名和时间
                Row(
                    horizontalArrangement = Arrangement.End,
                    modifier = Modifier.fillMaxWidth().padding(bottom = 5.dp)
                ) {
                    Text(text = TimeStringUtil.getTimeString(message.time), color = Color(0xFF656565), fontSize = 14.sp)
                    Spacer(modifier = Modifier.width(8.dp))
                    Text(text = message.userName, color = Color(0xFF656565), fontSize = 14.sp)
                }
                Row {
                    Spacer(modifier = Modifier.weight(1f))
                    //自己的消息气泡、消息内容
                    ContextTextShelf(text = message.content, easyChatTheme =easyChatTheme )
                }

            }
            //头像
            NetworkImage(
                url = message.userHeadImageUrl,
                painterFor = { remember { BitmapPainter(it) } },
                contentDescription = "头像",
                modifier = Modifier.size(40.dp).clip(CircleShape),
                contentScale = ContentScale.Crop,
                defaultPainterFor = painterResource("image/default_head.png")
            )
        }
    }
}

/**
 * 别人的消息气泡、消息内容
 */
@OptIn(ExperimentalComposeUiApi::class)
@Composable
fun ContextText(easyChatTheme: MutableState<EasyChatTheme>,text: String) {
    //在鼠标进入时，将消息的内容保存起来，为在用户没有进行文本选择的时候右键文本复制整个个消息
    val isActivity = remember { mutableStateOf(false) }
    val isFocus = remember { mutableStateOf(false) }
    //设置右键菜单的自定义样式及Item样式
    CompositionLocalProvider(LocalContextMenuRepresentation provides CustomLocalContextMenuRepresentation.current) {
        //设置右键菜单的自定义Item
        CustomTextMenuProvider {
            Box(modifier = Modifier.background(
                color = if (isFocus.value) easyChatTheme.value.contextTextFoursBg else easyChatTheme.value.contextTextBg,
                shape = RoundedCornerShape(10.dp)
            )
                .padding(14.dp)
                .onFocusChanged { isFocus.value = it.hasFocus }
                .onPointerEvent(PointerEventType.Enter) {
                    isActivity.value = true
                    //保存消息，为在用户没有进行文本选择的时候右键文本复制整个个消息
                    CustomTextContextMenu.copyText = text
                }
                .onPointerEvent(PointerEventType.Exit) { isActivity.value = false }
            ) {
                //声明文本选择区，可以在SelectionContainer中进行文本选择操作
                SelectionContainer {
                    Text(text = text)
                }
            }
        }
    }
}

/**
 * 自己的消息气泡、消息内容
 */
@OptIn(ExperimentalComposeUiApi::class, ExperimentalFoundationApi::class)
@Composable
fun ContextTextShelf(easyChatTheme: MutableState<EasyChatTheme>, text: String) {
    //在鼠标进入时，将消息的内容保存起来，为在用户没有进行文本选择的时候右键文本复制整个个消息
    val isActivity = remember { mutableStateOf(false) }
    val isFocus = remember { mutableStateOf(false) }
    //设置右键菜单的自定义样式及Item样式
    CompositionLocalProvider(LocalContextMenuRepresentation provides CustomLocalContextMenuRepresentation.current) {
        //设置右键菜单的自定义Item
        CustomTextMenuProvider {
            Box(modifier = Modifier.background(
                color = if (isFocus.value) easyChatTheme.value.contextTextFoursSelfBg else easyChatTheme.value.mainColor,
                shape = RoundedCornerShape(10.dp)
            )
                .padding(14.dp)
                .onFocusChanged { isFocus.value = it.hasFocus }
                .onPointerEvent(PointerEventType.Enter) {
                    isActivity.value = true
                    //保存消息，为在用户没有进行文本选择的时候右键文本复制整个个消息
                    CustomTextContextMenu.copyText = text
                }
                .onPointerEvent(PointerEventType.Exit) { isActivity.value = false }
            )
            {
                //声明文本选择区，可以在SelectionContainer中进行文本选择操作
                SelectionContainer {
                    Text(text = text)
                }
            }
        }
    }
}